package com.example.demo.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.example.demo.config.WxMaConfiguration;
import com.example.demo.util.Tools;
import com.example.demo.web.domain.BedInfo;
import com.example.demo.web.domain.BedRecord;
import com.example.demo.web.domain.VRecord;
import com.example.demo.web.domain.WxUser;
import com.example.demo.web.domain.form.LoginForm;
import com.example.demo.web.domain.model.AjaxResult;
import com.example.demo.web.mapper.BedInfoMapper;
import com.example.demo.web.mapper.BedRecordMapper;
import com.example.demo.web.mapper.VRecordMapper;
import com.example.demo.web.service.AppService;
import com.example.demo.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private UserService userService;

    @Autowired
    private BedRecordMapper bedRecordMapper;

    @Autowired
    private VRecordMapper vRecordMapper;

    @Autowired
    private BedInfoMapper bedInfoMapper;

    @Override
    public List<VRecord> bedList() {
        Example example = new Example(VRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(VRecord.DEL_FLAG, false);
        example.orderBy(BedInfo.BED_NO).asc();
        List<VRecord> records = vRecordMapper.selectByExample(example);
        if (Tools.listNotEmpty(records)) {
            for (VRecord record : records) {

            }
        }
        return records;
    }

    @Override
    @Transactional
    public AjaxResult login(LoginForm form) {
        final WxMaService wxService = WxMaConfiguration.getMaService(form.getAppId());
        try {
            // 根据用户的code和小程序的appid获取该用户对应小程序的唯一openid
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(form.getCode());
            WxUser wxUser = userService.selectUserByOpenId(session.getOpenid());
            if (wxUser == null) {
                // 创建用户
                wxUser = new WxUser();
                // 类型1医生2管理
                wxUser.setType("1");
                // 授权 默认未授权
                wxUser.setIsAuth(false);
            }
            wxUser.setOpenid(session.getOpenid());
            wxUser.setSessionKey(session.getSessionKey());
            wxUser.setNickName(form.getNickName());
            wxUser.setAvatarUrl(form.getAvatarUrl());
            wxUser.setMobile(form.getMobile());
            wxUser.setGender(form.getGender());
            wxUser.setCountry(form.getCountry());
            wxUser.setProvince(form.getProvince());
            wxUser.setCity(form.getCity());
            wxUser.setLanguage(form.getLanguage());
            if (wxUser.getId() != null) {
                userService.updateWxUser(wxUser);
            } else {
                userService.insertWxUser(wxUser);
            }
            return AjaxResult.success(wxUser);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error("授权失败!");
        }
    }

    @Override
    public AjaxResult saveOrUpdate(VRecord form) {
        if (form.getBedNo() == null) {
            return AjaxResult.error("床位号为空");
        }
        // 更新床位信息
        BedInfo bed = bedInfoMapper.selectByPrimaryKey(form.getBedNo());
        if (!bed.getBedName().equals(form.getBedName())) {
            bed.setBedName(form.getBedName());
            bed.setUpdateTime(new Date());
            bedInfoMapper.updateByPrimaryKeySelective(bed);
        }
        BedRecord record = new BedRecord();
        if (form.getId() != null) {
            // 更新当前记录
            record = bedRecordMapper.selectByPrimaryKey(form.getId());
            record.setPatientName(form.getPatientName());
            record.setGroupNo(form.getGroupNo().intValue());
            record.setInDate(form.getInDate());
            record.setUpdateTime(new Date());
            bedRecordMapper.updateByPrimaryKeySelective(record);
        } else {
            // 将该床位其他记录置为出院
            this.outHospital(form.getBedNo());
            // 添加当前记录
            record.setBedNo(bed.getBedNo());
            record.setPatientName(form.getPatientName());
            record.setGroupNo(form.getGroupNo().intValue());
            record.setInDate(form.getInDate());

            record.setState(true);// 在院状态
            record.setDelFlag(false);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            bedRecordMapper.insertSelective(record);
        }
        return AjaxResult.success();
    }

    /**
     * 出院
     *
     * @param bedNo
     */
    public AjaxResult outHospital(Long bedNo) {
        Example example = new Example(BedRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BedRecord.DEL_FLAG, false);
        criteria.andEqualTo(BedRecord.BED_NO, bedNo);
        List<BedRecord> records = bedRecordMapper.selectByExample(example);
        if (Tools.listNotEmpty(records)) {
            BedRecord param = new BedRecord();
            param.setState(false);
            param.setOutDate(new Date());
            bedRecordMapper.updateByExampleSelective(param, example);
        }
        return AjaxResult.success();
    }
}
